package main

import (
	"flag"
	"fmt"
	"github.com/mjiulee/lego"
	"log"
	"net/http"
	"saas_sys_base/modules/defaultSysConfig"

	"saas_sys_base/modules"
	"saas_sys_base/redishelper"
	//"runtime/pprof"
	"saas_sys_base/sysconfig"
	"strconv"

	_ "net/http/pprof"
	// "go/parser"
	// "go/token"

	middleware "saas_sys_base/modules/middleware"
)

var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
var webprofile = flag.String("webprofile", "", "program_name -webprofile")

func main() {
	var test string = "\x03\x00\x00\x13\x0e\xe0\x00\x00\x00\x00\x00\x01\x00\b\x00\x03\x00\x00\x00"
	var byTest []byte = []byte{0x03, 0x00, 0x00, 0x13, 0x0e, 0xe0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0b, 0x00, 0x03, 0x00, 0x00, 0x00}
	byTest = byTest
	test = test
	/*defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
		}
	}()*/

	//启动性能工具
	/*if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		fmt.Println("StartCPUProfile")
		defer func() {
			pprof.StopCPUProfile()
			fmt.Println("StopCPUProfile")
		}()


	}*/
	if *webprofile != "" {
		go func() {
			log.Println(http.ListenAndServe("0.0.0.0:6060", nil))
		}()
	}

	lego.UseAuthMiddleware(middleware.UserCheckTokenMiddleware, middleware.AppAuthMiddleware, middleware.TenantCheckMiddleware)
	lego.UseAdminMiddleware(middleware.AdminSaasMiddleware)
	//lego.UseMiddleware()
	/*fset := token.NewFileSet()
	f, err := parser.ParseFile(fset, "main.go", nil, parser.AllErrors)
	f = f
	err = err*/
	StartServer()

}

func StartServer() {
	// 初始化log
	lego.SetupLoggerBy("logconfig.xml")
	// 加载ini
	lego.LoadConfigFrom("appconfig.ini")

	// 同步数据库
	masterDbName := "master"
	masterDburl := sysconfig.Config.Database.Master_Db //lego.GetIniByKey(lego.K_GGF_CONFIG_DB_SECTION, lego.K_GGF_CONFIG_DB_MASTER)
	lego.SetUpSourceDatabase(masterDbName, []string{masterDburl}, true, true)
	lego.DoSynBeans(masterDbName)

	//初始化数据库，配置管理端菜单项

	defaultSysConfig.ConfigDefault()

	//为了初始化session与redis的关联
	redishelper.GetRedisConn()
	// 模块初始化
	// 显示模块加载信息
	modules.DoInit()

	// 新建一个服务对象
	server := lego.Server{}

	// 设置静态文件服务
	server.Static("/public", "static")
	server.Static("/view", "modules")
	// 及文件上传服务
	server.Static("/static", "upload")

	// 启动定时任务
	//go cron.StartTaskJops()
	fmt.Printf("server started on :%s \n", strconv.Itoa(sysconfig.Config.Http.Port))
	// 启动服务
	//server.Start(lego.GetIniByKey(lego.K_GGF_CONFIG_HTTP_SECTION, lego.K_GGF_CONFIG_HTTP_PORT), "saas_sys_base")
	server.Start(strconv.Itoa(sysconfig.Config.Http.Port), sysconfig.Config.APPName)
}
